package com.qys.livesMall.shop.controller.app;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.shop.constants.OrderStatus;
import com.qys.livesMall.shop.constants.OrderType;
import com.qys.livesMall.shop.mapper.ShopOrderReturnApprovedMapper;
import com.qys.livesMall.shop.modal.dto.*;
import com.qys.livesMall.shop.modal.entity.*;
import com.qys.livesMall.shop.modal.query.OrderApproverQuery;
import com.qys.livesMall.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gmx
 * @since 2023-06-23
 */
@RestController
@RequestMapping("/app/shopOrderReturnApproved")
@Validated
@Tag(name = "App-用户退货", description = "App-用户退货")
public class AppShopOrderReturnApprovedController {
    @Resource
    private ShopOrderReturnApprovedService approvedService;
    @Resource
    private ShopOrderReturnProcessService processService;
    @Resource
    private ShopOrderInfoService infoService;
    @Resource
    private ShopGoodsInfoService goodsInfoService;
    @Resource
    private ShopGoodsSkuService goodsSkuService;
    @Resource
    private ShopOrderReturnExpressService expressService;
    @Resource
    private ShopOrderSkuService skuService;

    @Autowired
    private ShopOrderInfoService shopOrderInfoService;
    @Resource
    private H2ShopBaseService baseService;

    @Resource
    private ShopOrderReturnApprovedMapper approvedMapper;

    @Autowired
    private ShopOrderStatusManager shopOrderStatusManager;

    @Autowired
    private ShopOrderSettlementInfoService shopOrderSettlementInfoService;

    @PostMapping("/add")
    @Operation(summary = "退货申请")
    @Transactional(rollbackFor = {Exception.class})
    public R add(@RequestBody OrderApproverDto orderApproverDto){
        try {
            LocalDateTime now = LocalDateTime.now();
            if (!orderApproverDto.getType().equals(OrderType.ReturnType.RETURN)
                    && !orderApproverDto.getType().equals(OrderType.ReturnType.EXCHANGE)
                    && !orderApproverDto.getType().equals(OrderType.ReturnType.REFUND)) {
                return R.fail(MessageUtils.message("select.type"));
            }
            ShopOrderReturnApproved approved=null;
            //判断是否是重复发起
            if (ObjectUtils.isNotEmpty(orderApproverDto.getId())){
                approved = approvedService.getById(orderApproverDto.getId());
                if (approved!=null&&!Objects.equals(approved.getOrderSkuId(),orderApproverDto.getOrderSkuId())){
                    throw new QysException(ExceptionEnum.PARAM_IS_ERROR);
                }
                if (approved!=null&& !Objects.equals(approved.getStatus(), OrderStatus.ReturnStatus.NO_PASS)){
                    return R.fail(MessageUtils.message("goods.return"));
                }
            }else {
                approved=approvedService.getByOrderSkuId(orderApproverDto.getOrderSkuId());
            }
            if(approved==null){
                approved = new ShopOrderReturnApproved();
            }
            ShopOrderSku sku = skuService.getById(orderApproverDto.getOrderSkuId());
            //退货
            if (orderApproverDto.getType().equals(OrderType.ReturnType.RETURN)){
                if (!sku.getOrderStatus().equals(OrderStatus.RECEIVED)) {
                    throw new QysException(MessageUtils.message("order.status.not.return"));
                }
            }
            //换货
            if (orderApproverDto.getType().equals(OrderType.ReturnType.EXCHANGE)){
                if (!sku.getOrderStatus().equals(OrderStatus.RECEIVED)) {
                    throw new QysException(MessageUtils.message("order.status.not.return"));
                }
            }
            ShopOrderInfo shopOrderInfo=shopOrderInfoService.getById(sku.getOrderId());
            if (null!= shopOrderInfo){
                approved.setOrderNoMain(shopOrderInfo.getOrderNo());
            }
            approved.setType(orderApproverDto.getType());
            approved.setOrderSkuId(orderApproverDto.getOrderSkuId());
            approved.setOrderNo(sku.getSkuOrderId());
            approved.setShopId(sku.getShopId());
            approved.setReturnUserId(SecurityUtils.getUserId());
            approved.setReturnUserName(SecurityUtils.getUsername());
            approved.setIdea(orderApproverDto.getIdea());
            approved.setDescription(orderApproverDto.getDescription());
            approved.setStatus(OrderStatus.ReturnStatus.APPLIED);
            approved.setCreateTime(now);
            approved.setUpdateTime(now);
            if (!approvedService.saveOrUpdate(approved))
                throw new QysException(MessageUtils.message("system.error.approved"));

            sku.setReturnBeforeStatus(sku.getOrderStatus());
            sku.setOrderStatus(OrderStatus.RETURN_APPLIED);
            skuService.updateById(sku);

            List<ShopOrderSku> skus= skuService.getStatusByOrderId(sku.getOrderId());
            ShopOrderInfo order=infoService.getById(sku.getOrderId());
            order.setOrderStatus(shopOrderStatusManager.getMainOrderStatus(skus));
            infoService.updateById(order);

            processService.add(approved.getId(),approved.getStatus(),approved.getType());
            return R.ok();
        }catch (QysException e){
            return R.fail(e.getMessage());
        }
    }
    @Operation(summary = "用户退货列表分页")
    @PostMapping("/page")
    public R<Page<OrderReturnDto>> list(@RequestBody OrderApproverQuery approverQuery){
        approverQuery.setReturnUserId(SecurityUtils.getUserId());
        Page<OrderReturnDto> page = Page.of(approverQuery.getCurrent(),approverQuery.getSize());
        Page<OrderReturnDto> list = approvedMapper.joinQuery(page,approverQuery);
        if (ObjectUtils.isEmpty(list.getRecords())){
            return R.ok(list);
        }
        for (int i = 0; i < list.getRecords().size(); i++) {
            OrderReturnDto record = list.getRecords().get(i);
            Long orderSkuId = record.getOrderSkuId();
            ShopOrderSku shopOrderSku = skuService.getById(orderSkuId);
            ShopOrderInfo shopOrderInfo=shopOrderInfoService.getById(shopOrderSku.getOrderId());
            if (ObjectUtils.isEmpty(shopOrderSku)){
                list.getRecords().remove(i);
                continue;
            }
            ShopOrderSkuDto skuDto = new ShopOrderSkuDto();
            BeanUtil.copyProperties(shopOrderSku,skuDto);
            ShopOrderDto orderDto=new ShopOrderDto();
            BeanUtil.copyProperties(shopOrderInfo,orderDto);
            ShopGoodsSku sku = goodsSkuService.getById(shopOrderSku.getSkuId());
            if (ObjectUtils.isNotEmpty(sku)){
                ShopGoodsInfo goods = goodsInfoService.getById(sku.getShopGoodsId());
                if (ObjectUtils.isEmpty(goods)){
                    record.setOrderSkuDto(skuDto);
                    continue;
                }
                skuDto.setGoodsDesc(goods.getGoodsDesc());
            }
            record.setOrderSkuDto(skuDto);
            record.setOrderDto(orderDto);
        }

        return R.ok(list);
    }
    @Operation(summary = "商铺退货列表分页")
    @PostMapping("/shoPage")
    public R<Page<OrderReturnDto>> shopList(@RequestBody OrderApproverQuery approverQuery){
        Long shopId = baseService.queryShopBaseIdByUserId(SecurityUtils.getUserId());
        approverQuery.setShopId(shopId);
        Page<OrderReturnDto> page = Page.of(approverQuery.getCurrent(),approverQuery.getSize());
        Page<OrderReturnDto> list = approvedMapper.joinQuery(page,approverQuery);
        for (OrderReturnDto record : list.getRecords()) {
            Long orderSkuId = record.getOrderSkuId();
            ShopOrderSku shopOrderSku = skuService.getById(orderSkuId);
            ShopOrderSkuDto skuDto = new ShopOrderSkuDto();
            ShopGoodsSku sku = goodsSkuService.getById(shopOrderSku.getSkuId());
            ShopGoodsInfo goods = goodsInfoService.getById(sku.getShopGoodsId());
            BeanUtil.copyProperties(shopOrderSku,skuDto);
            skuDto.setGoodsDesc(goods.getGoodsDesc());
            record.setOrderSkuDto(skuDto);
        }
        return R.ok(list);
    }
    @Operation(summary = "退货信息详情")
    @GetMapping("/{id}")
    public R<OrderReturnDto> get(@PathVariable Long id){
        OrderReturnDto returnDto= approvedMapper.joinQueryById(id);
        Long orderSkuId = returnDto.getOrderSkuId();
        ShopOrderSku shopOrderSku = skuService.getById(orderSkuId);
        ShopOrderSkuDto skuDto = new ShopOrderSkuDto();
        ShopGoodsSku sku = goodsSkuService.getById(shopOrderSku.getSkuId());
        ShopGoodsInfo goods = goodsInfoService.getById(sku.getShopGoodsId());
        BeanUtil.copyProperties(shopOrderSku,skuDto);
        skuDto.setGoodsDesc(goods.getGoodsDesc());
        returnDto.setOrderSkuDto(skuDto);
        return R.ok(returnDto);
    }
    @Operation(summary = "取消退货")
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public R delete(@PathVariable Long id){
        ShopOrderReturnApproved approved=approvedService.getById(id);
        if (ObjectUtils.isEmpty(approved))return R.fail(MessageUtils.message("shop.order.null"));
        if (!approved.getStatus().equals(OrderStatus.ReturnStatus.APPLIED)
                && !approved.getStatus().equals(OrderStatus.ReturnStatus.CONFIRMED)) {
            return R.fail(MessageUtils.message("order.status.not.return"));
        }

        ShopOrderSku sku=skuService.getById(approved.getOrderSkuId());
        sku.setOrderStatus(sku.getReturnBeforeStatus());
        skuService.updateById(sku);
        ShopOrderInfo orderInfo=infoService.getById(sku.getOrderId());
        List<ShopOrderSku> skus=skuService.getByOrderId(sku.getOrderId());
        orderInfo.setOrderStatus(shopOrderStatusManager.getMainOrderStatus(skus));
        infoService.updateById(orderInfo);

        approved.setStatus(OrderStatus.ReturnStatus.CANCELED);
        approved.setUpdateTime(LocalDateTime.now());
        if(!approvedService.updateById(approved)){
            throw new QysException(MessageUtils.message("system.error.approved"));
        }
        processService.add(approved.getId(),approved.getStatus(),approved.getType());
         return R.ok();
    }
//    @Operation(summary = "商铺退货单操作")
//    @PostMapping("/handel")
//    @Transactional(rollbackFor = {Exception.class})
//    public R handle(@RequestBody OrderHandelVO handelVO){
//        ShopOrderReturnApproved approved = approvedService.getById(handelVO.getApprovedId());
//        approved.setProcessUser(0);
//        ShopOrderReturnProcess process = new ShopOrderReturnProcess();
//        BeanUtil.copyProperties(handelVO,process);
//        process.setUserId(SecurityUtils.getUserId());
//        process.setUserName(SecurityUtils.getUsername());
//        process.setProcessUser(0);
//        process.setCreateTime(LocalDateTime.now());
//        process.setUpdateTime(LocalDateTime.now());
//        if(!processService.save(process))return R.fail("system error");
//        if(!approvedService.updateById(approved))throw new QysException("system error");
//        return R.ok();
//    }
    @Operation(summary = "退货-用户发货")
    @PostMapping("/returnShipped")
    @Transactional(rollbackFor = {Exception.class})
    public R returnShipped(@RequestBody ShopOrderReturnExpressDto expressDto){
        try {
            ShopOrderReturnApproved approved=approvedService.getById(expressDto.getApprovedId());
            if (ObjectUtils.isEmpty(approved))return R.fail(MessageUtils.message("shop.order.null"));
            if (!approved.getStatus().equals(OrderStatus.ReturnStatus.CONFIRMED)) {
                return R.fail(MessageUtils.message("order.status.not.return"));
            }

            LocalDateTime now = LocalDateTime.now();
            LambdaQueryWrapper<ShopOrderReturnExpress> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ShopOrderReturnExpress::getApprovedId,expressDto.getApprovedId());
            queryWrapper.eq(ShopOrderReturnExpress::getShipper,2);
            ShopOrderReturnExpress exp = expressService.getOne(queryWrapper);
            ShopOrderReturnExpress express = new ShopOrderReturnExpress();
            BeanUtil.copyProperties(expressDto,express);
            express.setShipper(2);
            if (ObjectUtils.isNotEmpty(exp)){
                express.setApprovedId(exp.getApprovedId());
            }
            if(!expressService.saveOrUpdate(express))return R.fail(MessageUtils.message("system.error.express"));

            approved.setStatus(OrderStatus.ReturnStatus.USER_SHIPPED);
            approved.setUpdateTime(now);
            if(!approvedService.updateById(approved)) throw new QysException(MessageUtils.message("system.error.approved"));

            processService.add(approved.getId(),approved.getStatus(),approved.getType());
            return R.ok();
        }catch (QysException e){
            return R.fail(e.getMessage());
        }

    }

    @Operation(summary = "换货-用户收货")
    @PostMapping("/returnReceived")
    @Transactional(rollbackFor = {Exception.class})
    public R returnReceived(@RequestBody ShopOrderReturnExpressDto expressDto){
        try {
            ShopOrderReturnApproved approved=approvedService.getById(expressDto.getApprovedId());
            if (ObjectUtils.isEmpty(approved))return R.fail(MessageUtils.message("shop.order.null"));
            if (!approved.getStatus().equals(OrderStatus.ReturnStatus.PLATFORM_SHIPPED)) {
                return R.fail(MessageUtils.message("order.status.not.return"));
            }

            LocalDateTime now = LocalDateTime.now();
            LambdaQueryWrapper<ShopOrderReturnExpress> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ShopOrderReturnExpress::getApprovedId,expressDto.getApprovedId());
            queryWrapper.eq(ShopOrderReturnExpress::getShipper,2);
            ShopOrderReturnExpress exp = expressService.getOne(queryWrapper);
            ShopOrderReturnExpress express = new ShopOrderReturnExpress();
            BeanUtil.copyProperties(expressDto,express);
            if (ObjectUtils.isNotEmpty(exp)){
                express.setApprovedId(exp.getApprovedId());
            }
            if(!expressService.saveOrUpdate(express))return R.fail(MessageUtils.message("system.error.express"));

            approved.setStatus(OrderStatus.ReturnStatus.USER_RECEIVED);
            approved.setUpdateTime(now);
            if(!approvedService.updateById(approved)) throw new QysException(MessageUtils.message("system.error.approved"));

            processService.add(approved.getId(),approved.getStatus(),approved.getType());

            //自动完成
            approvedService.autoFinish(approved.getId());
            //更新订单结算状态
            ShopOrderSettlementInfo settlementInfo=shopOrderSettlementInfoService.getByOrderId(approved.getOrderSkuId());
            if (settlementInfo!=null&&Objects.equals(settlementInfo.getStatus(), Constants.YesNoInt.NO)){
                settlementInfo.setStatus(2);
                shopOrderSettlementInfoService.updateById(settlementInfo);
            }
            return R.ok();
        }catch (QysException e){
            return R.fail(e.getMessage());
        }

    }

//    @GetMapping("/process/{id}")
//    public R<List<OrderReturnDto>> ListProcess(@PathVariable Long id){
//        QueryReturn qr =  new QueryReturn();
//        qr.setId(id);
//        List<OrderReturnDto> res = approvedMapper.joinQueryProcess(qr);
//        return R.ok(res);
//    }
    @GetMapping("/process/{approvedId}")
    public R<List<ShopOrderReturnProcess>> process(@PathVariable("approvedId") Long approvedId){
        LambdaQueryWrapper<ShopOrderReturnProcess> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopOrderReturnProcess::getApprovedId,approvedId);
        queryWrapper.orderByDesc(ShopOrderReturnProcess::getCreateTime);
        List<ShopOrderReturnProcess> list = processService.list(queryWrapper);

        return R.ok(list);
    }

    @Operation(summary = "运单号查询")
    @GetMapping("/express/{id}")
    public R<ShopOrderReturnExpress> express(@PathVariable Long id){
        LambdaQueryWrapper<ShopOrderReturnExpress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopOrderReturnExpress::getApprovedId,id);
        ShopOrderReturnExpress exp = expressService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(exp)){
            return R.fail(MessageUtils.message("express.null"));
        }
        return R.ok(exp);
    }

}
